package com.rtp2p.rtcoresdkdemo.main

import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.LifecycleOwner
import com.rtp2p.rtcoresdkdemo.play.LivePlayActivity
import com.rtp2p.rtcoresdkdemo.base.BaseRecyclerView
import com.rtp2p.rtcoresdkdemo.databinding.MainItemBinding
import com.rtp2p.rtcoresdkdemo.replay.ReplayActivity
import com.rtp2p.rtp2pcore.core.BindingDevice

class MainAdapter(private val onLoadDevices: () -> Unit) :
    BaseRecyclerView.BaseAdapter<MainAdapter.DeviceInfo, MainAdapter.MainVH>() {
    data class DeviceInfo(val deviceId: String, val deviceName: String, val isAp: Boolean = false)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainVH {
        val binding = MainItemBinding.inflate(LayoutInflater.from(parent.context))
        binding.lifecycleOwner = parent.context as LifecycleOwner
        return MainVH(binding)
    }

    override fun onBindViewHolder(holder: MainVH, position: Int) {
        getData(position)?.let { holder.update(it) }
    }

    inner class MainVH(binding: MainItemBinding) :
        BaseRecyclerView.BaseViewHolder<DeviceInfo, MainItemBinding>(binding) {
        override fun onChange(data: DeviceInfo) {
            binding.deviceId = data.deviceId
            binding.deviceName = data.deviceName
            binding.livePlay.setOnClickListener {
                val intent = Intent(context, LivePlayActivity::class.java)
                intent.putExtra("deviceId", data.deviceId)
                intent.putExtra("isAp", data.isAp)

                context.startActivity(intent)
            }
            binding.replay.setOnClickListener {
                val intent = Intent(context, ReplayActivity::class.java)
                intent.putExtra("deviceId", data.deviceId)
                intent.putExtra("isAp", data.isAp)

                context.startActivity(intent)
            }
            binding.delete.setOnClickListener {
                val bindingDevice = BindingDevice()
                bindingDevice.delete(data.deviceId) {
                    if (it.success) {
                        onLoadDevices()
                        Toast.makeText(context,"${data.deviceId} 删除成功",Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context,"${data.deviceId} 删除失败",Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }
}